package cn.fntop.config;

import cn.fntop.entity.Data;
import cn.fntop.entity.R;
import cn.fntop.utils.EmailUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Component
public class FileListener extends FileAlterationListenerAdaptor {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private ToEmail toEmail;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.switch}")
    private Boolean onMail;


    /**
     * 文件创建执行
     */
    @SneakyThrows
    @Override
    public void onFileCreate(File file) {
        log.info("[新建]:" + file);
    }
 
    /**
     * 文件创建修改
     */
    @Override
    public void onFileChange(File file) {
        log.info("[修改]:" + file.getAbsolutePath());
        String jsonString = null;
        try {
            //已经实现读取json文本数据到json对象的转化
            jsonString = new String(Files.readAllBytes(Paths.get(file.getPath())));
            R<Data> res = JSON.parseObject(jsonString, R.class);
            //todo json 文本数据处理
            //json数据符合条件或邮件开关开启则发送邮件
            if (onMail) {
                //发送邮件通知
                String[] tos = toEmail.getTos();
                if (tos != null && tos.length > 0) {
                    EmailUtil emailUtil = new EmailUtil(mailSender);
                    emailUtil.commonEmail(toEmail, from);
                }
            }
        } catch (IOException e) {
            log.error("读取文件失败。。。");
        }

    }
 
    /**
     * 文件删除
     */
    @Override
    public void onFileDelete(File file) {
        log.info("[删除]:" + file.getAbsolutePath());
    }
 
    /**
     * 目录创建
     */
    @Override
    public void onDirectoryCreate(File directory) {
        log.info("[新建]:" + directory.getAbsolutePath());
    }
 
    /**
     * 目录修改
     */
    @Override
    public void onDirectoryChange(File directory) {
        log.info("[修改]:" + directory.getAbsolutePath());
    }
 
    /**
     * 目录删除
     */
    @Override
    public void onDirectoryDelete(File directory) {
        log.info("[删除]:" + directory.getAbsolutePath());
    }
 
    @Override
    public void onStart(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStart(observer);
    }
 
    @Override
    public void onStop(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStop(observer);
    }
}